#! /bin/bash
# Desc : 将某个文件中的数据导入到cmsrv中
# Usage : import_nodes.sh deffile
# the def file example:
#
# cluster click_cluster click_server
# node 127.0.0.1 null node1 dn_cluster
#
#

usage() 
{
    echo ""
    echo "usage:"
    echo " import_nodes.sh deffile "
    echo "    deffile - 节点定义文件参看 nodes.def.example"
    echo ""
}

NodeFile=$1
if [ -z "$NodeFile" ]; then
    echo "please specify the deffile"
    usage
    exit 1
fi

# makesure the cmssrv is running
CmsrvApp=`ps aux | grep beam.smp | grep cmsrvapp`

if [ -z "$CmsrvApp" ]; then
    echo "the cmsrv not running"
    exit 1
fi

# process the deffile
add_to_cmsrv()
{
    while read aline; do
        type=`echo $aline | cut -d ' ' -f 1`
        #echo "line is $aline"
        if [ "$type" = "cluster" ]; then
            Cmd=$(echo $aline | awk '{if(NF == 4)
                                        printf "./cmsrvctl add_cluster %s %s %s", $2, $3, $4;
                                      else if(NF == 3)
                                        printf "./cmsrvctl add_cluster %s %s", $2, $3
                                    }')
                                        
            echo -e "add_cluster: $Cmd ... "
        elif [ "$type" = "node" ]; then
            Cmd=$(echo $aline | awk '{printf "./cmsrvctl add_node %s %s %s %s", $2, $3, $4, $5}')
            echo -e "add_node: $Cmd ... "
        else
            echo "first field $tpye is invalid"
            exit 1
        fi

        eval "$Cmd"
        if [ $? -eq 0 ]; then
            echo "ok"
        else
            echo "error! ret: $?"
        fi
        echo ""
    done
}

add_to_cmsrv < $NodeFile

echo "complete!"
